<script lang="ts" setup>
import formPage from "./formPage.vue";
import { addItem } from "../service";
import { IResponseData } from "@/@types/utils.request";
import { ElMessage, ElMessageBox } from "element-plus";

const props = defineProps({
	modelValue: {
		type: Boolean,
		default: false,
	},
	nutritionItemList: {
		type: Array<{
			projectName: string;
			projectId: number;
		}>,
		default: () => [],
	},
	staffTitleList: {
		type: Array<{
			id: number;
			name: string;
		}>,
		default: () => [],
	},
	institutionList: {
		type: Array<{ id: number; name: string }>,
		default: () => [],
		required: true,
	},
	serviceType: {
		type: Array<{ id: number; name: string }>,
		default: () => [],
		required: true,
	},
});

// 新增数据
const insertData = ref({
	doctorName: "",
	doctorPhone: "",
	institutionId: "",
	departmentName: "",
	staffTitleId: "",
	doctorIdcard: "",
	serviceTypeStr: [],
	graphicPrice: "",
	expertiseIntro: "",
	workingYear: "",
	doctorIntro: "",
	doctorIcon: "",
	doctorPic: "",
	doctorStaffPic: "",
	recommend: "",
	projectIds: [],
	sort: 0,
	isShow: 0,
});

const emit = defineEmits<{
	(e: "update:modelValue", value: boolean): void;
	(e: "refresh", value: boolean): void;
}>();
const visible = computed({
	get() {
		return props.modelValue;
	},
	set(val) {
		emit("update:modelValue", !!val);
	},
});
const formRef = ref<any>();
const onConfirmm = async () => {
	if (!(await formRef.value.validate())) return;
	try {
		const response: IResponseData<any> = await addItem({
			...insertData.value,
		});
		const { code, msg } = response;
		if (code === 0) {
			ElMessage({
				message: msg,
				type: "success",
			});
			formRef.value.resetFields();
			emit("refresh", true);
			emit("update:modelValue", false);
		} else {
			ElMessage({
				message: msg,
				type: "error",
			});
		}
	} catch (error: any) {
		console.log(error);
	}
};

const onCancel = () => {
	ElMessageBox.confirm("您所编辑的内容还未保存，此时退出会导致修改内容失效，确定要退出吗？", {
		confirmButtonText: "确认",
		cancelButtonText: "取消",
		type: "warning",
	}).then(() => {
		formRef.value.resetFields();
		emit("update:modelValue", false);
	});
};
</script>
<template>
	<el-dialog v-model="visible" title="新增" top="10vh" width="700px" :before-close="onCancel">
		<formPage
			v-model="insertData"
			:serviceType="serviceType"
			:institutionList="institutionList"
			:nutritionItemList="nutritionItemList"
			:staffTitleList="staffTitleList"
			ref="formRef"
		/>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="onCancel">取消</el-button>
				<el-button type="primary" @click="onConfirmm"> 确认 </el-button>
			</span>
		</template>
	</el-dialog>
</template>
